package com.luckylo.activemq.config;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.MessageType;

import javax.jms.ConnectionFactory;

/**
 * @user: luckylo
 * @date: 2018-1-17
 */

@Configuration
public class ActiveMQConfig {

    @Value("${activemq.url}")
    private String url;

    @Value("${activemq.user}")
    private String user;

    @Value("${activemq.password}")
    private String pass;

    @Bean
    // 初始化连接
    public ConnectionFactory factory() {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
        factory.setBrokerURL(url);
        factory.setUserName(user);
        factory.setPassword(pass);
        return factory;
    }


    @Bean
    @SuppressWarnings("SpringJavaAutowiringInspection")
    // topic 发布订阅模式; queue 队列模式
    public JmsListenerContainerFactory<?> topicListenerFactory(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setMessageConverter(messageConverter());
        factory.setConnectionFactory(connectionFactory);
        //"true" for the Publish/Subscribe domain(发布订阅模式)
        factory.setPubSubDomain(true);
        return factory;
    }

    @Bean
    // 使用 TextMessage 将 message 序列化成 json
    public MessageConverter messageConverter() {
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        converter.setTargetType(MessageType.TEXT);
        converter.setTypeIdPropertyName("_type");
        return converter;
    }


}
